package initialize

import (
	"fmt"
	"go_final/mxshop_srvs/order_srv/global"
	goodspb "go_final/mxshop_srvs/order_srv/proto/protofile/goods"
	inventorypb "go_final/mxshop_srvs/order_srv/proto/protofile/inventory"

	_ "github.com/mbobakov/grpc-consul-resolver" // It's important
	"go.uber.org/zap"
	"google.golang.org/grpc"
)

// InitSrvConnWithLoadBalance 负载均衡拉取服务
func InitSrvConnWithLoadBalance() {
	goodsConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s",
			global.ServerConfig.ConsulInfo.Host,
			global.ServerConfig.ConsulInfo.Port,
			global.ServerConfig.GoodsSrvInfo.Name,
		),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Info("[InitSrvConnWithLoadBalance] 连接 【商品服务不可用】失败")
	}

	global.GoodsSrvClient = goodspb.NewGoodsClient(goodsConn)

	invConn, err := grpc.Dial(
		fmt.Sprintf("consul://%s:%d/%s?wait=14s",
			global.ServerConfig.ConsulInfo.Host,
			global.ServerConfig.ConsulInfo.Port,
			global.ServerConfig.InventorySrvInfo.Name,
		),
		grpc.WithInsecure(),
		grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy": "round_robin"}`),
	)
	if err != nil {
		zap.S().Info("[InitSrvConnWithLoadBalance] 连接 【商品服务不可用】失败")
	}

	global.InvSrvClient = inventorypb.NewInventoryClient(invConn)
}
